<template>
  <div>

    <el-button
      type="primary"
      size="mini"
      @click="onAdd"
    >
      新增
    </el-button>

    <custom-table
      :current-page.sync="currentPage"
      :table-props="{
        size: 'mini',
        border: true,
      }"
      :data="list.rows"
      :columns="columns"
      :total="list.total"
      :page-size.sync="pageSize"
      @update:currentPage="onPageChange"
      @update:pageSize="onPageSizeChange"
    >
      <template v-slot="{ row, col }">
        <el-tag v-if="col.prop === 'name'">{{ row[col.prop] }}</el-tag>
        <template v-if="col.prop === 'op'">
          <el-button
            size="mini"
            @click="onPermission(row.id)"
          >
            分配权限
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="onEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="onDelete(row.id)"
          >
            删除
          </el-button>
        </template>
      </template>
    </custom-table>

    <!-- 新增弹窗 -->
    <el-dialog
      :title="editingId === -1 ? '新增角色' : '编辑角色'"
      :visible.sync="addVisible"
      @close="closeAddDialog"
    >
      <el-form
        :model="addParams"
        :rules="addRules"
        label-width="80px"
      >
        <el-form-item
          label="角色名称"
          prop="name"
        >
          <el-input v-model="addParams.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="description"
        >
          <el-input v-model="addParams.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddDialog">取 消</el-button>
        <el-button type="primary" @click="onAddOk">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 权限弹窗 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="permissionVisible"
      destroy-on-close
    >
      <i v-if="permissionLoading" class="el-icon-loading" />
      <el-tree
        v-else
        ref="permissionTree"
        :data="permissionList"
        show-checkbox
        default-expand-all
        check-strictly
        node-key="id"
        :default-checked-keys="permission"
        :props="{
          children: 'children',
          label: 'name',
        }"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="closePermissionDialog">取 消</el-button>
        <el-button type="primary" @click="onPermissionOk">确 定</el-button>
      </div>
    </el-dialog>

    <el-button @click="exportExcel">
      导出excel
    </el-button>

    <el-button @click="importExcel">
      导入excel
    </el-button>

    <!-- 导入excel弹窗 -->
    <el-dialog title="导入excel" :visible.sync="importExcelVisible">
      <el-upload
        drag
        action="https://jsonplaceholder.typicode.com/posts/"
        multiple
        :before-upload="onBeforeUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import * as api from '@/api/role';
import ExcelJS from 'exceljs';
import FileSaver from 'file-saver';
import readXlsxFile from 'read-excel-file';

// 封装函数 封装一样的部分 不一样的部分当作参数
// 不一样的部分 1. 变量
// 不一样的部分 2. 逻辑(函数) callback

// 先找想要的东西 return
// 换上参数

function getCheckFunc(field) {
  return function(rule, value, callback) {
    if (!value) {
      callback(new Error(this.$t('companySetting.dialogTip.add.' + field)))
    } else {
      callback()
    }
  }
}

// function checkValue1 (rule, value, callback) {
//   if (!value) {
//     callback(new Error(this.$t('companySetting.dialogTip.add.name')))
//   } else {
//     callback()
//   }
// }

// function checkValue2 (rule, value, callback) {
//   if (!value) {
//     callback(new Error(this.$t('companySetting.dialogTip.add.description')))
//   } else {
//     callback()
//   }
// }

export default {
  computed: {
    ...mapState('role', [
      'list',
      'permissionList',
      'permission'
    ])
  },
  data() {
    return {
      // 导入excel弹窗是否显示
      importExcelVisible: false,
      // 正在编辑的id
      editingId: -1,
      // 分配权限loading
      permissionLoading: false,
      currentPage: 1,
      pageSize: 5,
      addVisible: false,
      addParams: {
        name: '',
        description: ''
      },
      addRules: {
        name: [{ required: true, trigger: 'blur', validator: getCheckFunc('name').bind(this) }],
        description: [{ required: true, trigger: 'blur', validator: getCheckFunc('description').bind(this) }]
      },
      permissionVisible: false,
      columns: [
        {
          label: '序号',
          // 没有prop的时候 显示索引
          width: 200
        },
        {
          label: '角色',
          prop: 'name',
          needSlot: true
        },
        // table column配置项
        {
          label: '描述',
          prop: 'description',
          sortable: true,
          resizable: true
        },
        {
          label: '操作',
          prop: 'op', // 暂时没用的
          needSlot: true
        }
      ]
    }
  },
  methods: {
    ...mapActions('role', [
      'updateList',
      'updatePermissionList',
      'updatePermission'
    ]),
    importExcel () {
      this.importExcelVisible = true;
    },
    // 导入excel
    onBeforeUpload (file) {
      readXlsxFile(file).then((rows) => {
        console.log(rows);
      })
    },
    // 导出excel
    async exportExcel() {
      // 我们有的数据
      const data = this.list.rows
      const wb = new ExcelJS.Workbook()
      const ws = wb.addWorksheet('zhangsan')

      ws.columns = this.columns.slice(1, -1).map(col => ({
        header: col.label,
        key: col.prop
      }))

      ws.addRows(data)

      // 文件里的编码
      const buffer = await wb.xlsx.writeBuffer()

      const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
      const blob = new Blob([buffer], { type: EXCEL_TYPE })

      FileSaver.saveAs(blob, '嘿嘿.xlsx')
    },
    // 关闭权限弹窗
    closePermissionDialog() {
      this.permissionVisible = false
    },
    // 权限确定按钮
    async onPermissionOk() {
      const idList = this.$refs.permissionTree.getCheckedKeys()
      const res = await api.setRolePermission(editingId, idList)
      this.$message({
        message: res.message,
        type: res.success ? 'success' : 'error'
      })
      if (res.success) {
        // 关弹窗
        this.closePermissionDialog()
      }
    },
    // 动态生成表格行样式
    getRowClassName(rowInfo) {
      const colorList = ['red', 'green', 'yellow']
      const idx = rowInfo.rowIndex % colorList.length
      return colorList[idx]
      // if (rowInfo.rowIndex % 2 === 1) {
      //   return 'red';
      // }
      // return '';
    },
    // 分页切换
    onPageChange(currentPage) {
      this.updateList({
        page: currentPage,
        pagesize: this.pageSize
      })
    },
    onPageSizeChange(size) {
      this.currentPage = 1
      this.updateList({
        page: 1,
        pagesize: size
      })
    },
    // 新增确定
    async onAddOk() {
      // 通过当前的模式来判断发哪个请求
      let res
      if (this.editingId === -1) {
        res = await api.add(this.addParams)
      } else {
        res = await api.edit({
          id: this.editingId,
          ...this.addParams
        })
      }
      this.$message({
        message: res.message,
        type: res.success ? 'success' : 'error'
      })
      if (res.success) {
        // 关弹窗
        this.closeAddDialog()
        // 刷新列表
        this.updateList({
          page: this.currentPage,
          pagesize: this.pageSize
        })
      }
    },
    // 关闭新增弹窗
    closeAddDialog() {
      this.addVisible = false
      // 置空数据
      this.addParams = {
        name: '',
        description: ''
      }
    },
    // 新增
    onAdd() {
      this.addVisible = true
      // 修改为新增模式
      this.editingId = -1
    },
    // 编辑
    onEdit(rowData) {
      this.addVisible = true
      // 反显
      this.addParams.name = rowData.name
      this.addParams.description = rowData.description
      // 记录当前正在编辑的id  修改为编辑模式
      this.editingId = rowData.id
    },
    // 删除
    onDelete(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await api.remove(id)
          this.$message({
            message: res.message,
            type: res.success ? 'success' : 'error'
          })
          if (res.success) {
          // 刷新列表
            this.updateList({
              page: this.currentPage,
              pagesize: this.pageSize
            })
          }
        })
        .catch(() => {})
    },
    // 分配权限
    async onPermission(id) {
      editingId = id
      // 打开弹窗
      this.permissionVisible = true
      // 开启loading
      this.permissionLoading = true
      // 获取角色权限
      await this.updatePermission(id)
      // 关闭loading
      this.permissionLoading = false
    }
  },
  created() {
    this.updateList({
      page: this.currentPage,
      pagesize: this.pageSize
    })
    // 拿权限列表数据
    this.updatePermissionList()
  }
}

</script>

<style lang="scss" scoped>
::v-deep .red {
  background: rgba(0, 0, 0, .1);
}
::v-deep .green {
  background: rgba(0, 0, 0, .15);
}
::v-deep .yellow {
  background: rgba(0, 0, 0, .2);
}
</style>
